package com.bls.productmall.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bls.productmall.entity.Order;
import com.bls.productmall.entity.Product;
import com.bls.productmall.enums.OrderStatus;
import com.bls.productmall.mapper.OrderMapper;
import com.bls.productmall.mapper.ProductMapper;
import com.bls.productmall.service.OrderService;
import com.bls.productmall.util.OrderNoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.Instant;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private ProductMapper productMapper;

    /**
    * 根据产品id来生成订单
    * */
    @Override
    public Order createOrderByProductIdAndUserId(Long productId, Long userId) {
        //查找已存在但未支付的订单
        Order order = this.getNoPayOrderByProductId(productId, userId);
        if( order != null){
            return order;
        }
        //获取商品信息
        Product product = productMapper.selectById(productId);
        //生成订单
        order = new Order();
        order.setTitle(product.getTitle());
        order.setOrderNo(OrderNoUtils.getOrderNo()); //订单号
        order.setPaymentType("微信支付"); //支付类型
        order.setUserId(userId);  //用户id
        order.setUserDelete(1); // 用户是否删除
        order.setProductId(productId);
        order.setTotalFee(product.getPrice()); //分
        order.setOrderStatus(OrderStatus.NOTPAY.getType());
        baseMapper.insert(order);
        return order;
    }

    /**
     * 存储订单二维码
     */
    @Override
    public void saveCodeUrl(String orderNo, String codeUrl) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        Order order = new Order();
        order.setCodeUrl(codeUrl);
        baseMapper.update(order, queryWrapper);
    }

    /**
     * 查询订单列表，并倒序查询
     */
    @Override
    public List<Order> listOrderByCreateTimeDesc() {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().orderByDesc("create_time");
        return baseMapper.selectList(queryWrapper);
    }

    /**
    * 根据用户id和用户是否删除来查询订单列表
    */
    @Override
    public List<Order> listOrderByUserIdAndUserDelete(Long userId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("user_delete", 1);
        return baseMapper.selectList(queryWrapper);
    }

    /**
    * 用户根据订单id删除订单（只是将user_delete改为0）
    * */
    @Override
    public Order userDeleteOrder(String orderNo){
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        Order order = new Order();
        order.setUserDelete(0);
        String orderStatus = this.getOrderStatus(orderNo);
        order.setOrderStatus(orderStatus+"，用户已删除");
        baseMapper.update(order, queryWrapper);
        return order;
    }

    /**
     * 根据订单号更新订单状态
     */
    @Override
    public void updateStatusByOrderNo(String orderNo, OrderStatus orderStatus) {
        log.info("更新订单状态 ===> {}", orderStatus.getType());
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        Order order = new Order();
        order.setOrderStatus(orderStatus.getType());
        baseMapper.update(order, queryWrapper);
    }

    /**
     * 根据订单号获取订单状态
     */
    @Override
    public String getOrderStatus(String orderNo) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        Order order = baseMapper.selectOne(queryWrapper);
        if(order == null){
            return null;
        }
        return order.getOrderStatus();
    }

    /**
     * 查询创建超过minutes分钟并且未支付的订单
     */
    @Override
    public List<Order> getNoPayOrderByDuration(int minutes) {
        Instant instant = Instant.now().minus(Duration.ofMinutes(minutes));
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_status", OrderStatus.NOTPAY.getType());
        queryWrapper.le("create_time", instant);
        List<Order> orderList = baseMapper.selectList(queryWrapper);
        return orderList;
    }

    /**
     * 根据订单号获取订单
     */
    @Override
    public Order getOrderByOrderNo(String orderNo) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        Order order = baseMapper.selectOne(queryWrapper);
        return order;
    }


    /**
     * 根据商品id和用户id查询未支付订单
     * 防止重复创建订单对象
     */
    private Order getNoPayOrderByProductId(Long productId, Long userId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("order_status", OrderStatus.NOTPAY.getType());
        Order order = baseMapper.selectOne(queryWrapper);
        return order;
    }
}
